
import time 
import sys 
from threading import Thread 

from ctypes import cdll as dll, byref, c_char_p, c_void_p
from ctypes import create_string_buffer, create_unicode_buffer
from ctypes import Structure, POINTER
from ctypes import c_int, c_uint8, c_uint16, c_uint32, c_uint64, c_double

## define structures used :
class CameraResult(Structure):
	_fields_ = [
		('interval', c_double),
		('status', c_int),
		('x', c_int),
		('y', c_int),
		]

class RawPixel(Structure):
	_fields_ = [
		('r', c_uint8),
		('g', c_uint8),
		('b', c_uint8),
		]

class HSV(Structure):
	_fields_ = [
		('h', c_uint8),
		('s', c_uint8),
		('v', c_uint8),
		]
	def __str__(self):
		return '[%s, %s, %s]' % (self.h, self.s, self.v,)
	__repr__ = __str__

class Filter(Structure):
	_fields_ = [
		('top', HSV),
		('bottom', HSV),
		]
	def __str__(self):
		return '<filter> t %s : b %s' % (self.top, self.bottom, )
	__repr__ = __str__

class MouseEvent(Structure):
	_fields_ = [
		('triggered', c_int),
		('event', c_int),
		('x', c_int),
		('y', c_int),
		('flags', c_int),
		('pixel', RawPixel),
		('converted', HSV),
		]

camera_lib = dll.camera
print camera_lib

class CameraDevice:
	def __init__(self, camera_index, filename):
		self._device = None
		## setup foreign functions ..
		self._initialize = camera_lib.initialize
		self._initialize.restype = c_void_p
		self._UNinitialize = camera_lib.UNinitialize
		self._run_camera = camera_lib.run_camera
		self._run_camera.restype = CameraResult
		
		## parse :
		filters = self._parse_file_parameters(filename)
		if len(filters) != 4:
			raise Exception('config format error ..')
		
		print 'dump config: '
		for x in filters: print x
		
		## call initialize :
		address = self._initialize(camera_index, filters[0], filters[1], filters[2], filters[3])
		if not address: raise Exception('CAMERA missing ..')
		self._device = c_void_p(address)
		print 'device %r - %r' % (self._device, type(self._device),)
	
	def __del__(self):
		if self._device != None:
			self._UNinitialize(self._device)
			self._device = None
	
	def run(self, type):
		if self._device != None:
			ret = self._run_camera(self._device, type)
			return ret 

	def cleanup(self):
		if self._device != None:
			self._UNinitialize(self._device)
			self._device = None
	
	def _parse_file_parameters(self, filename):
		""" file format : r ,g ,b, e | high, low
		"""
		f = open( filename, 'rb' )
		data = f.read()
		data = data.replace(' ', '')
		data = data.replace('\n', '')
		data = data.replace('\r', '')
		q = data.split(',')
		ret = []
		for x in range(4):
			ret.append( Filter( (int(q[3]), int(q[4]), int(q[5]),), (int(q[0]), int(q[1]), int(q[2]),), ) )
			q = q[6:]
		return ret 


global WORKING
WORKING = True

TYPE_ENUM = {
	'RED'	: 0,
	'GREEN' : 1,
	'BLUE'	: 2,
	'EMPTY'	: 3,
	'BROWN'	: 4,
	}

if __name__ == '__main__':
	
	def KeyBreak():
		global WORKING
		data = raw_input('press enter to break ..\n')
		WORKING = False

	t = Thread(target = KeyBreak)
	t.setDaemon(True)

	camera = CameraDevice(0, 'bojenove.txt')
	begin = time.time()
	
	type = TYPE_ENUM['RED']
	
	t.start()
	while WORKING:
		result = camera.run(type)
		if result.status :
			print ' + %s, %s [%s]s' % (result.x, result.y, result.interval, )

	camera.cleanup()
	import sys 
	sys.exit()












